
import { useEffect, useState, useRef } from 'react'
import { Form, Tooltip, Switch, Row, Col, TreeSelect, message } from 'antd'
import { QuestionCircleOutlined } from '@ant-design/icons'
import bus from '../../../../utils/eventBus'
import './index.scss'
const PowerManage = () => {
    const formRef = useRef<any>(null)
    const treeResolve = useRef<any>(null)
    const treeKey = useRef<any>(null)
    const timer = useRef<any>(null)
    const cacheData = useRef<any>(null)
    const [treeData, setTreeData] = useState<any[]>([])
    const onLoadData = ({ key = '', children, id = '' }: any) => {
        return new Promise<void>(resolve => {
            treeResolve.current = resolve
            if (children) {
                resolve();
                return
            }
            const params = {
                id: id ? id : '',
            };
            treeKey.current = key
            window.chromePro.getUserTree(JSON.stringify(params));
        })
    }
    const updateTreeData = (list: any[], key: string, children: any[]): any[] => {
        if (!key) {
            return [...children]
        }
        return list.map(node => {
            if (node.key === key) {
                return {
                    ...node,
                    children
                }
            }
            if (node.children) {
                return {
                    ...node,
                    children: updateTreeData(node.children, key, children)
                }
            }
            return {
                ...node
            }
        })
    }
    const getUserTreeFinished = (res: any) => {
        if (res.code === 200) {
            if (!res.data.length) return treeResolve.current && treeResolve.current()
            res.data.map((item: any) => {
                item.label = item.caption
                item.title = item.caption
                item.value = item.id
                item.key = item.id
                if (item.type === 'organization') {
                    item.disabled = true
                } else {
                    item.isLeaf = true
                }
            })
            setTreeData(origin => updateTreeData(origin, treeKey.current, [...res.data]))
            treeResolve.current && treeResolve.current(undefined)
        } else {
            message.error(res.msg)
        }
    }
    const handleChange = (value: any[]) => {
        const users: any[] = []
        value.map(item => {
            users.push({
                id: item.value,
                name: item.label
            })
        })
        cacheData.current = users
        handleSubmit()
    }
    const handleSubmit = () => {
        const { enable, users } = formRef.current.getFieldsValue()
        const params = {
            enable,
            users: cacheData.current
        }
        if (!users || !users.length && !enable) {
            message.warning('授权用户为空时，不允许开启授权权限')
            params.enable = false
            formRef.current.setFieldsValue({
                enable: false
            })
        }
        if (timer.current) {
            clearTimeout(timer.current)
        }
        timer.current = setTimeout(() => {
            window.chromePro.setRecoveryConfig(JSON.stringify(params))
        }, 1000)
    }
    const setRecoveryConfigFinished = (res: any) => {
        if (res.code === 200) {
            message.success('设置成功')
        } else {
            message.error(res.msg)
        }
    }
    const getRecoveryConfigFinished = (res: any) => {
        if (res.code === 200) {
            const { enable, users } = res.data
            const data: any[] = []
            if (users.length) {
                JSON.parse(users).map((item: any, index: number) => {
                    data.push({
                        label: item.name,
                        value: item.id
                    })
                })
            }
            formRef.current.setFieldsValue({
                enable,
                users: data
            })
            cacheData.current = users.length ? JSON.parse(users) : null
        } else {
            message.error(res.msg)
        }
    }
    const switchChange = (val: boolean) => {
        handleSubmit()
    }
    useEffect(() => {
        window.chromePro.getRecoveryConfig(JSON.stringify({}));
        onLoadData({})
        bus.addListener('getUserTreeFinished', getUserTreeFinished)
        bus.addListener('setRecoveryConfigFinished', setRecoveryConfigFinished)
        bus.addListener('getRecoveryConfigFinished', getRecoveryConfigFinished)
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener('getUserTreeFinished', getUserTreeFinished)
            bus.removeListener('setRecoveryConfigFinished', setRecoveryConfigFinished)
            bus.removeListener('getRecoveryConfigFinished', getRecoveryConfigFinished)
        }
    }, [])
    return (
        <>
            <div className="power-manage">
                <div className="menu-title">权限管理</div>
                <div className="power-recycle">
                    <div className="power-recycle-top">
                        <span></span>
                        <span>回收权限</span>
                        <Tooltip overlayClassName='tooltip-power' color="white" title={'启用回收权限,个人将无法回收。'} placement="right">
                            <QuestionCircleOutlined />
                        </Tooltip>
                    </div>
                    <div className="recycle-action">
                        <Form ref={formRef} style={{ width: '100%' }}>
                            <Row gutter={24}>
                                <Col span={4}>
                                    <Form.Item valuePropName='checked' label="" name="enable" style={{ marginBottom: 0 }}>
                                        <Switch onChange={switchChange} checkedChildren="开启" unCheckedChildren="关闭" />
                                    </Form.Item>
                                </Col>
                                <Col span={16}>
                                    <Form.Item name="users" style={{ marginBottom: 0 }} label="授权用户" labelCol={{ span: 4 }}>
                                        <TreeSelect treeDataSimpleMode labelInValue treeCheckStrictly onChange={handleChange} treeCheckable="true" loadData={onLoadData} placeholder="请选择授权用户" multiple treeData={treeData}></TreeSelect>
                                    </Form.Item>
                                </Col>
                            </Row>
                        </Form>
                    </div>
                </div>
            </div>
        </>
    )
}
export default PowerManage